﻿
$(function ()
{

    $('.btn-lookup').click(function ()
    {
        var etn = $(this).attr("etn").toLowerCase(); //关系实体名称
        core.Lookup.FromId = $(this).parent().prev().attr("id"); //lookup字段名称
        core.Lookup.BindLookupList(etn);

        $("#LookupModal").modal({ backdrop: 'static', keyboard: false, show: true });

    });
});

core.Lookup = {}
core.Lookup.EntityField;
core.Lookup.EntityName;
core.Lookup.Orderby = null;
core.Lookup.ListData;
core.Lookup.FromId;
core.Lookup.EntityOption;
core.Lookup.Selected = null;
core.Lookup.NowSelectedNode = null;
core.Lookup.CustomSelectedFunctionList = {};
core.Lookup.GetSelectedOid = function ()
{

    return core.Lookup.Selected["oid"];
}
//初始化LookupList
core.Lookup.BindLookupList = function (etn)
{
    $(".modal").attr("etn", etn);
    $("#modal-title-etn").text(etn);
    core.Lookup.Orderby = null;
    core.Lookup.Selected = null;

    $("#LookupListContainer thead").html("");
    $("#LookupListContainer tbody").html("");
    $("#txt_lookupsearchValue").val("");



    core.Lookup.EntityName = etn;

    core.Lookup.BindListHeader(etn);
}

core.Lookup.BindListHeader = function (etn)
{

    core.Lookup.FilterData = { "Conditions": [], "FilterOperator": "AND", "Filters": [] };  //清空搜索条件
    $.ajax({
        type: "post",
        url: "/Service/Data/GetEntityField.ashx",
        dataType: "json",
        data: { entityname: etn, viewname: "LookupView" },
        success: function (data, textStatus)
        {
            var EntityField = data["Fields"];
            core.Lookup.EntityField = data["Fields"];
            core.Lookup.EntityOption = data["Options"];
            var colNullTemplate = '<col {0} ></col>';
            var colsHTML = '<col width="35px"></col>';
            var colsWidth = 35;
            var listHeaderTemplate = '<th class="{2}" attname="{3}" {4}>{0} {1}</th>'
            var listHeaders = "<th></th>";
            $.each(EntityField, function (i, v)
            {
                var width = (v.AttributeWidth == undefined || v.AttributeWidth == "") ? "" : v.AttributeWidth;
                colsWidth += (v.AttributeWidth == undefined || v.AttributeWidth == "") ? 200 : v.AttributeWidth * 1;
                colsHTML += $.format(colNullTemplate, width == "" ? "" : 'width="' + width + 'px"');
                switch (v.Type)
                {
                    case "nvarchar":
                    case "int":
                    case "float":
                    case "bit":
                    case "lookup":
                    case "date":
                    case "datetime":
                    case "picklist":

                        if (core.Lookup.Orderby == null && v.IsPrimaryAtt)
                            core.Lookup.Orderby = { att: i, value: 'asc' };
                        if (core.Lookup.Orderby != null && core.Lookup.Orderby.att == i)
                            listHeaders += String.format(listHeaderTemplate, v.DisplayName, '<span class="glyphicon"><span>', 'th-sort th-sort-' + core.Lookup.Orderby.value, i, 'onclick="core.Lookup.Sort(this)"');
                        else
                            listHeaders += String.format(listHeaderTemplate, v.DisplayName, '<span class="glyphicon"><span>', 'th-sort', i, 'onclick="core.Lookup.Sort(this)"');
                        break;
                    case "ntext":
                        listHeaders += String.format(listHeaderTemplate, v.DisplayName, null, null, null, null);
                        break;
                    case "key":
                        //listHeaders += String.format(listHeaderTemplate, "");
                        break;
                }
            });
            $("#LookupListContainer colgroup").html(colsHTML);
            $("#LookupListContainer-title thead").html(String.format('<tr>{0}</tr>', listHeaders));
            $("#LookupListContainer-title").css("width", colsWidth);
            $("#LookupListContainer-body").css("width", colsWidth);
            core.Lookup.BindListItem(etn);
        },
        error: function ()
        {
        }
    });
}


core.Lookup.BindListItem = function (etn, filter, pagenum, pagesize)
{
    if (pagesize == null || pagesize == undefined) pagesize = 50;
    order = String.format("{0} {1} "
        , core.Lookup.Orderby.att + (core.Lookup.EntityField[core.Lookup.Orderby.att].Type == "lookup" ? "name" : "")
        , core.Lookup.Orderby.value);
    $.ajax({
        type: "post",
        url: "/Service/Data/GetListData.ashx",
        dataType: "json",
        data: { entityname: etn, "filter": JSON.stringify(filter), order: order, pagenum: pagenum, pagesize: pagesize, viewname: "LookupView" },
        success: function (data, textStatus)
        {

            //core.View.BindListPageing();

            var ListData = data;
            core.Lookup.ListData = ListData;
            var rowTemplate = '<tr etn="{0}" oid="{1}">{2}</tr>'
            var colCheckBoxTemplate = '<td><input type="checkbox" onchange="core.Lookup.LookupChecked(this);" etn="{0}" oid="{1}" value="{2}" data-json=\'{3}\'/></td>';
            var colTextTemplate = '<td>{0}</td>';
            var colPickTemplate = '<td>{0}</td>';
            var colUniqueTemplate = '<td><a href="#" etn="{0}" oid="{1}" onclick="core.OpenEntity(this);"><span class="glyphicon glyphicon-tags small"></span> {2}</a></td>';

            var colBitTemplate = '<td>{0}</td>';

            var rows = "";
            $.each(ListData.List, function (i, v)
            {
                var cols = String.format(colCheckBoxTemplate, etn, v[etn + "id"], v[core.Lookup.GetPrimaryAtt()], JSON.stringify(v));
                $.each(core.Lookup.EntityField, function (key, value)
                {
                    switch (value.Type)
                    {
                        case "nvarchar":
                        case "int":
                        case "date":
                        case "datetime":
                        case "float":
                            if (value.IsPrimaryAtt)
                                cols += String.format(colUniqueTemplate, etn, v[etn + "id"], v[key]);
                            else
                                cols += String.format(colTextTemplate, v[key]);
                            break;
                        case "ntext":
                            cols += String.format(colTextTemplate, v[key]);
                            break;
                        case "picklist":
                            cols += String.format(colPickTemplate, core.Lookup.GetOptionText(core.Lookup.EntityOption[key], v[key]));
                            break;
                        case "bit":
                            cols += String.format(colBitTemplate, v[key] ? '是' : '否');
                            break;
                        case "lookup":
                            if (v[key] == null)
                            {
                                cols += "<td></td>";
                            }
                            else
                            {
                                cols += String.format(colUniqueTemplate, v[key]["entityname"], v[key]["id"], v[key]["name"]);
                            }
                            break;
                        case "key":
                            //listHeaders += String.format(listHeaderTemplate, "");
                            break;
                    }
                });
                rows += String.format(rowTemplate, etn, v[etn + "id"], cols);
            })
            $("#LookupListContainer-body tbody").html(rows);

            core.Lookup.BindListPageing();
        },
        error: function ()
        {
        }
    });
}


core.Lookup.Search = function ()
{
    var searchValue = $("#txt_lookupsearchValue").val();
    if (searchValue != "")
    {
        var Filter = { "Conditions": [], "FilterOperator": "OR" };
        $.each(core.Lookup.EntityField, function (key, v)
        {
            if (v.Type != 'datetime' && v.Type != 'date' && v.Type != 'picklist')
            {
                var ConditionExpression = { "AttributeName": key, "Operator": "like" };
                if (v.Type == 'lookup')
                {
                    var lookup = { "Name": "*" + searchValue, "id": null };
                    ConditionExpression["Values"] = [lookup];
                }
                else
                {
                    ConditionExpression["Values"] = ["*" + searchValue];
                }
                Filter["Conditions"].push(ConditionExpression);
            }
        });
        core.Lookup.FilterData["Filters"] = [Filter];
    }
    if (searchValue == "")
    {
        core.Lookup.FilterData = { "Conditions": [], "FilterOperator": "AND", "Filters": [] };  //清空搜索条件
        core.Lookup.BindListItem(core.Lookup.EntityName, null);
    }
    else
    {
        core.Lookup.BindListItem(core.Lookup.EntityName, core.Lookup.FilterData);
    }
}

core.Lookup.GetPrimaryAtt = function ()
{
    var primaryAtt = "";
    $.each(core.Lookup.EntityField, function (i, v)
    {
        if (v.IsPrimaryAtt)
        {
            primaryAtt = i;
            return false;
        }
    });
    return primaryAtt;

}


core.Lookup.BindListPageing = function ()
{
    var pageingTemplate = '{0}\\{1}';
    var total = core.Lookup.ListData.Total;
    var size = core.Lookup.ListData.Size;
    var index = total == 0 ? 0 : core.Lookup.ListData.Index + 1;
    var pages = Math.ceil(total / size);
    $("#pageInfo").text(String.format(pageingTemplate, index, pages));
    if (total != 0)
    {
        $("#pageFirst").parent().removeClass("disabled");
        $("#pagePrevious").parent().removeClass("disabled");
        $("#pageLast").parent().removeClass("disabled");
        $("#pageNext").parent().removeClass("disabled");
        if (index == 1)
        {
            $("#pageFirst").parent().addClass("disabled");
            $("#pagePrevious").parent().addClass("disabled");
        }
        if (index == pages)
        {
            $("#pageLast").parent().addClass("disabled");
            $("#pageNext").parent().addClass("disabled");
        }
    }
    else
    {
        $("#pageFirst").parent().addClass("disabled");
        $("#pagePrevious").parent().addClass("disabled");
        $("#pageLast").parent().addClass("disabled");
        $("#pageNext").parent().addClass("disabled");
    }
}


core.Lookup.NextPage = function ()
{
    if (!$("#pageNext").parent().hasClass("disabled"))
    {
        core.Lookup.BindListItem(core.Lookup.EntityName, core.Lookup.FilterData, core.Lookup.ListData.Index + 1);
    }
}

core.Lookup.PrePage = function ()
{
    if (!$("#pagePrevious").parent().hasClass("disabled"))
    {
        core.Lookup.BindListItem(core.Lookup.EntityName, core.Lookup.FilterData, core.Lookup.ListData.Index - 1);
    }
}

core.Lookup.LastPage = function ()
{
    if (!$("#pageLast").parent().hasClass("disabled"))
    {
        var total = core.Lookup.ListData.Total;
        var size = core.Lookup.ListData.Size;
        var pages = Math.ceil(total / size);
        core.Lookup.BindListItem(core.Lookup.EntityName, core.Lookup.FilterData, pages - 1);
    }

}

core.Lookup.FirstPage = function ()
{
    if (!$("#pageFirst").parent().hasClass("disabled"))
    {
        core.Lookup.BindListItem(core.Lookup.EntityName, core.Lookup.FilterData, 0);
    }
}

core.Lookup.GetOptionText = function (options, value)
{
    var text = "";
    $.each(options, function (i, v)
    {
        if (v.Value == value)
        {
            text = v.Text;
            return false;
        }
    });
    return text;
}


core.Lookup.SelectedLookup = function ()
{

    if (typeof (core.Lookup.CustomSelectedLookup) != 'undefined' || core.Lookup.CustomSelectedLookup != null)
    {
        try
        {
            core.Lookup.CustomSelectedLookup();
            return;
        } catch (e)
        {

        }
    }
    try
    {
        if (typeof (core.Lookup.CustomSelectedFunctionList[core.Lookup.FromId]) == 'function')
        {
            core.Lookup.CustomSelectedFunctionList[core.Lookup.FromId]({
                detail: {
                    id: core.Lookup.Selected["oid"],
                    name: core.Lookup.Selected["value"],
                    elem: core.Lookup.FromId,
                    data: JSON.parse(core.Lookup.Selected['jsondata'])
                }
            });
            return;
        }
    } catch (e)
    {

    }


    //$(".modal").modal("hide");
    if (core.Lookup.Selected != null)
    {
        $("#" + core.Lookup.FromId).attr("oid", core.Lookup.Selected["oid"]);
        $("#" + core.Lookup.FromId).val(core.Lookup.Selected["value"]);
        $("#" + core.Lookup.FromId).change();
    } else
    {
        $("#" + core.Lookup.FromId).attr("oid", '');
        $("#" + core.Lookup.FromId).val('');
        $("#" + core.Lookup.FromId).change();
    }
}
core.Lookup.LookupChecked = function (src)
{

    if ($(src).is(":checked"))
    {
        $("#LookupListContainer-body input[type=checkbox]").attr("checked", false);
        $(src).prop("checked", true);
        core.Lookup.Selected = { oid: $(src).attr("oid"), value: $(src).val(), jsondata: $(src).attr('data-json') };
        core.Lookup.NowSelectedNode = src;
    }
    else
    {
        core.Lookup.Selected = null;
        core.Lookup.NowSelectedNode = null;
    }
}

core.Lookup.Sort = function (src)
{
    var $this = $(src);
    if ($this.attr("attname") != core.Lookup.Orderby.att)
    {
        var $curSort = $this.parent().find(".th-sort[attname=" + core.Lookup.Orderby.att + "]");
        $curSort.removeClass("th-sort-asc");
        $curSort.removeClass("th-sort-desc");
        $this.addClass("th-sort-asc");
        core.Lookup.Orderby.value = "asc";
        core.Lookup.Orderby.att = $this.attr("attname");
    }
    else
    {
        if ($this.hasClass("th-sort-asc"))
        {
            $this.removeClass("th-sort-asc");
            $this.addClass("th-sort-desc");
            core.Lookup.Orderby.value = "desc";
        }
        else
        {
            $this.removeClass("th-sort-desc");
            $this.addClass("th-sort-asc");
            core.Lookup.Orderby.value = "asc";
        }
    }
    core.Lookup.BindListItem(core.Lookup.EntityName, core.Lookup.FilterData);
};

